﻿// Copyright (c) Inossem. All rights reserved.
// Licensed under the LGPL-3.0 license. See LICENSE file in the project root for full license information.
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace DWF.Studio.Share.Serialization
{
    public static class JsonHelper
    {
        public static string Serialize(object obj)
        {
            string json = JsonConvert.SerializeObject(obj);

            return json;
        }

        public static string SerializeWithTypeName(object obj)
        {
            string json = JsonConvert.SerializeObject(obj, Formatting.Indented, new JsonSerializerSettings
            {
                TypeNameHandling = TypeNameHandling.All
            });

            return json;
        }

        public static T Deserialize<T>(string json)
        {
            var obj = JsonConvert.DeserializeObject<T>(json);

            return obj;
        }

        public static T DeserializeWithTypeName<T>(string json)
        {
            var obj = JsonConvert.DeserializeObject<T>(json, new JsonSerializerSettings
            {
                TypeNameHandling = TypeNameHandling.Auto
            });

            return obj;
        }

        public static T DeserializeFloatAsDecimal<T>(string json)
        {
            var obj = JsonConvert.DeserializeObject<T>(json, new JsonSerializerSettings
            {
                TypeNameHandling = TypeNameHandling.Auto,
                FloatParseHandling = FloatParseHandling.Decimal
            });

            return obj;
        }

        public static string Format(string json)
        {
            dynamic parsedJson = JsonConvert.DeserializeObject(json);
            return JsonConvert.SerializeObject(parsedJson, Formatting.Indented);
        }

        /// <summary>
        /// 解析成JObject对象  Oliver add 2021-06-18
        /// </summary>
        /// <param name="json"></param>
        /// <returns></returns>
        public static bool ContainItem(string json, string itemName)
        {
            var obj = JObject.Parse(json);
            return obj[itemName] != null;
        }
    }
}
